<?php

namespace App\Middlewares;

use App\Exceptions\BizException;
use App\Exceptions\NotLoginException;
class CheckLoginMiddleware implements \Base\MiddlewareInterface
{
    public static function handle(\Base\BaseController &$controller)
    {
        $params = array_merge(
            $controller->request()->getParsedBody(),
            $controller->request()->getQueryParams()
        );
        $token = $params['accesstoken'];
        $notLogin = config('whitelist.notLogin');
        $path = $controller->request()->getUri()->getPath();
        $mustLogin = !in_array($path, $notLogin);
        $controller->needLogin = $mustLogin;
        if ($mustLogin && !$token) {
            throw new NotLoginException();
        }

        $userFromRedis = \Lib\RedisManager::init()->get(config('keys.redis.USER_TOKEN') . $token);
        if ($mustLogin && empty($userFromRedis)) {
            throw new NotLoginException();
        }
        $user = json_decode(base64_decode($userFromRedis), true);
        if ($mustLogin && (!isset($user['id']) || $user['id'] <= 0)) {
            throw new NotLoginException();
        }
        $userid = $user['id'];
        $user = (new \App\Models\UserModel())->getUserByUid($userid, "*");
        if ($mustLogin && empty($user)) {
            throw new BizException("微信登录失败", BizException::PLEASE_RE_WX_LOGIN);
        }
        $controller->userinfo = $user;
        $controller->uid = $user['id'];
        $controller->params['login_uid'] = $user['id'];
    }
}
